package com.stupidzhe.vbreview.controller.adm;

import com.stupidzhe.vbreview.bean.ResultBean;
import com.stupidzhe.vbreview.bean.ZipResultBean;
import com.stupidzhe.vbreview.domain.Class;
import com.stupidzhe.vbreview.domain.Project;
import com.stupidzhe.vbreview.domain.ProjectClassRecord;
import com.stupidzhe.vbreview.domain.Teacher;
import com.stupidzhe.vbreview.service.ClassService;
import com.stupidzhe.vbreview.service.ProjectClassRecordService;
import com.stupidzhe.vbreview.service.ProjectService;
import com.stupidzhe.vbreview.util.FileUtil;
import com.stupidzhe.vbreview.util.Md5Util;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;

import static com.stupidzhe.vbreview.constant.ProjectConst.HOST;

@Controller
@RequestMapping(value = "/adm/project")
public class AdmProjectController {

    private final Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");

    private final ProjectService projectService;
    private final ProjectClassRecordService projectClassRecordService;
    private final ClassService classService;

    public AdmProjectController(ProjectService projectService, ProjectClassRecordService projectClassRecordService, ClassService classService) {
        this.projectService = projectService;
        this.projectClassRecordService = projectClassRecordService;
        this.classService = classService;
    }


    @RequestMapping(value = "/", headers = {"Referer=" + HOST + "/adm/"})
    public String mainView(@RequestParam(defaultValue = "1", required = false) Integer pageNum,
                           @RequestParam(required = false) String keyword, Model model, HttpServletRequest request) {
        Teacher teacher = (Teacher) request.getAttribute("teacher");
        model.addAttribute("pageBean", projectService.getProjectPage(pageNum, teacher.getUserId(), keyword));
        model.addAttribute("keyword", keyword);
        return "adm/adm.project";
    }

    /**
     * 作业添加页面
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String addView() {
        return "adm/adm.project.add";
    }

    //处理文件上传
    @RequestMapping(value = "/uploadDoc", method = RequestMethod.POST)
    @ResponseBody
    public ResultBean uploadDoc(@RequestParam(value = "docFile") MultipartFile file,
                                HttpServletRequest request) {
        String contentType = file.getContentType();
        String fileName = file.getOriginalFilename();
        String[] nameArr = fileName.split("[.]");
        if (!nameArr[nameArr.length - 1].equals("doc")
                && !nameArr[nameArr.length - 1].equals("docx")
                && !nameArr[nameArr.length - 1].equals("pdf")
                && !nameArr[nameArr.length - 1].equals("txt")) {
            return new ResultBean(false, "文件格式出错");
        }
        String name = null;
        try {
            name = FileUtil.uploadFile(file.getBytes(), Md5Util.getPwd(String.valueOf(System.currentTimeMillis())), nameArr[nameArr.length - 1]);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultBean(false, e.getMessage());
        }
        //返回json
        if (null == name) {
            return new ResultBean(false, "上传失败");
        }
        return new ResultBean(true, name);
    }

    @RequestMapping(value = "/uploadProject", method = RequestMethod.POST)
    @ResponseBody
    public ResultBean uploadProject(@RequestParam(value = "projectFile") MultipartFile file,
                                    HttpServletRequest request) {
        String fileName = file.getOriginalFilename();
        String[] nameArr = fileName.split("[.]");
        if (!nameArr[nameArr.length - 1].equals("rar")
                && !nameArr[nameArr.length - 1].equals("zip")) {
            return new ResultBean(false, "文件格式出错");
        }
        String name = null;
        ZipResultBean zipResultBean;
        try {
            zipResultBean = FileUtil.unzip(file.getBytes(), nameArr[0], nameArr[nameArr.length - 1]);
            if (!zipResultBean.isSuccess()) {
                return new ResultBean(false, zipResultBean.getMsg());
            }
            return new ResultBean(true, zipResultBean.getName());

        } catch (Exception e) {
            e.printStackTrace();
            return new ResultBean(false, e.getMessage());

        }
    }

    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ResultBean add(@RequestParam(value = "projectName") String projectName,
                          @RequestParam(value = "expression", required = false) String expression,
                          @RequestParam(value = "classification", defaultValue = "0") Integer classification,
                          @RequestParam(value = "demoLocation") String demoLocation,
                          @RequestParam(value = "upTimesMax") String upTimesMax,
                          @RequestParam(value = "docLocation", required = false) String docLocation, HttpServletRequest request) {
        if ("".equals(projectName.trim())) {
            return new ResultBean(false, "作业名称不能为空");
        }
        if ("".equals(demoLocation.trim())) {
            return new ResultBean(false, "作业样例不能为空");
        }
        if (!pattern.matcher(upTimesMax).matches()) {
            return new ResultBean(false, "字符串非法");
        }

        Teacher teacher = (Teacher) request.getAttribute("teacher");
        return projectService.add(projectName, classification, expression, demoLocation, docLocation, Integer.valueOf(upTimesMax), teacher.getUserId());
    }

    @ResponseBody
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public ResultBean edit(HttpServletRequest request,
                           @PathVariable(value = "id") Integer projectId,
                           @RequestParam(value = "projectName", required = false) String projectName,
                           @RequestParam(value = "expression", required = false) String expression,
                           @RequestParam(value = "demoLocation", required = false) String demoLocation,
                           @RequestParam(value = "docLocation", required = false) String docLocation,
                           @RequestParam(value = "status", required = false) String status,
                           @RequestParam(value = "upTimesMax", required = false) String upTimesMax,
                           @RequestParam(value = "classArr", required = false) String classArr) {
        String[] arr = null;
        if (classArr != null) {
            arr = classArr.split(",");
            List<Integer> iList = new ArrayList<>(arr.length);
            List<Boolean> bList = new ArrayList<>(arr.length);
            try {
                for (String i : arr) {
                    iList.add(Integer.valueOf(i.split("[:]")[0]));
                    bList.add(Boolean.valueOf(i.split("[:]")[1]));
                }
            } catch (Exception e) {
                return new ResultBean(false, "字符串非法");
            }
        }
        if (status != null && !status.equals("0") && !status.equals("1")) {
            return new ResultBean(false, "字符串非法");
        }
        if (upTimesMax != null && !pattern.matcher(upTimesMax).matches()) {
            return new ResultBean(false, "字符串非法");
        }
        Teacher teacher = (Teacher) request.getAttribute("teacher");
        try {
            if (arr == null) {
                return projectService.editProject(projectId, projectName, docLocation, demoLocation, expression, teacher.getUserId(), null, status, upTimesMax);
            } else {
                return projectService.editProject(projectId, projectName, docLocation, demoLocation, expression, teacher.getUserId(), Arrays.asList(arr), status, upTimesMax);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultBean(false, "更新失败");
        }
    }

    /**
     * 详情页
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String detail(@PathVariable("id") Integer projectId, Model model, HttpServletRequest request) {
        Teacher teacher = (Teacher) request.getAttribute("teacher");
        Project project = projectService.getProjectById(projectId);
        model.addAttribute("project", project);
        List<ProjectClassRecord> list = projectClassRecordService.getListByProjectId(projectId);
        model.addAttribute("pcList", list);
        List<Class> classList = classService.getClassByTeacherId(teacher.getUserId());
        model.addAttribute("classList", classList);
        return "adm/adm.project.detail";
    }

    @RequestMapping("/file/")
    public String getFile(@RequestParam("fileName") String fileName, HttpServletResponse response) {
        File file = FileUtil.getFile(fileName);
        if (!file.exists() || file.isDirectory()) {
            return null;
        }
        response.setContentType("application/force-download");
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
        byte[] buffer = new byte[1024];
        FileInputStream fis = null; //文件输入流
        BufferedInputStream bis = null;
        OutputStream os = null; //输出流
        try {
            os = response.getOutputStream();
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer);
                i = bis.read(buffer);
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

}
